<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生成绩详情</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4f46e5',
                        secondary: '#64748b',
                        accent: '#10b981',
                        danger: '#ef4444',
                        light: '#f8fafc',
                        dark: '#0f172a',
                        chinese: '#3b82f6',
                        math: '#10b981', 
                        english: '#8b5cf6',
                        physics: '#f59e0b',
                        chemistry: '#ef4444'
                    }
                }
            }
        }
    </script>
    
    <style>
        .card-shadow {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        .gradient-bg {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
        }
        .fade-in {
            animation: fadeIn 0.3s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .subject-header {
            @apply px-5 py-4 flex justify-between items-center font-semibold rounded-t-lg;
        }
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 8px;
            color: white;
            z-index: 1000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        }
        .toast.show {
            transform: translateX(0);
        }
        .toast.success { background-color: #10b981; }
        .toast.error { background-color: #ef4444; }
        .toast.warning { background-color: #f59e0b; }
    </style>
</head>
<body class="bg-gray-50 font-sans">
    <!-- 顶部导航 -->
    <nav class="gradient-bg text-white shadow-lg">
        <div class="container mx-auto px-4 py-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3">
                    <i class="fa fa-graduation-cap text-2xl"></i>
                    <h1 class="text-xl font-bold">学生成绩管理系统</h1>
                </div>
                <button onclick="goBack()" class="bg-white/20 hover:bg-white/30 text-white px-4 py-2 rounded-lg transition duration-200 flex items-center">
                    <i class="fa fa-arrow-left mr-2"></i> 返回列表
                </button>
            </div>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="container mx-auto px-4 py-8">
        <!-- 详情页内容区域 -->
        <div id="detailSection">
            <!-- 页面标题和操作区 -->
            <div class="mb-8">
                <div class="flex flex-col md:flex-row md:items-center justify-between mb-6">
                    <div>
                        <h2 class="text-2xl font-bold text-dark" id="studentNameTitle">学生成绩详情</h2>
                        <p class="text-secondary" id="studentCampus">校区信息</p>
                    </div>
                </div>
            </div>

            <!-- 加载状态 -->
            <div id="loadingState" class="text-center py-12">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 mb-4">
                    <i class="fa fa-spinner fa-spin text-primary text-2xl"></i>
                </div>
                <p class="text-gray-500">加载中...</p>
            </div>

            <!-- 学生概览卡片 -->
            <div id="overviewCard" class="bg-white rounded-xl shadow-md p-6 mb-8 hidden fade-in">
                <h3 class="text-lg font-semibold mb-4 pb-2 border-b border-gray-100">成绩概览</h3>
                <div class="grid grid-cols-2 md:grid-cols-6 gap-4" id="overviewContainer">
                    <!-- 成绩概览将通过JS动态生成 -->
                </div>
            </div>

            <!-- 成绩详情卡片 -->
            <div id="scoresCard" class="bg-white rounded-xl shadow-md p-6 mb-8 hidden fade-in">
                <h3 class="text-lg font-semibold mb-6 pb-2 border-b border-gray-100">各科成绩记录</h3>
                <div class="space-y-6" id="scoresContainer">
                    <!-- 成绩内容将通过JS动态生成 -->
                </div>
            </div>

            <!-- 空状态 -->
            <div id="emptyState" class="hidden text-center py-20">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                    <i class="fa fa-user-o text-gray-400 text-2xl"></i>
                </div>
                <p class="text-gray-500 text-lg">暂无成绩数据</p>
            </div>

            <!-- 错误状态 -->
            <div id="errorState" class="hidden text-center py-20">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-100 mb-4">
                    <i class="fa fa-exclamation-triangle text-red-400 text-2xl"></i>
                </div>
                <p class="text-red-500 text-lg" id="errorMessage">加载失败</p>
                <button onclick="loadStudentDetail()" class="mt-4 text-primary hover:text-primary/80 transition duration-200">
                    <i class="fa fa-refresh mr-1"></i> 重新加载
                </button>
            </div>
        </div>
    </div>

    <!-- 添加/编辑成绩模态框 -->
    <div id="examModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl w-full max-w-md mx-4 transform scale-95 transition-transform duration-300">
            <div class="p-6 border-b border-gray-100">
                <h3 class="text-xl font-bold text-dark" id="modalTitle">添加成绩</h3>
            </div>
            <div class="p-6">
                <input type="hidden" id="editScoreId">
                <input type="hidden" id="currentSubjectId">
                <div class="mb-5">
                    <label class="block text-sm font-medium text-gray-700 mb-1">分数</label>
                    <input type="number" step="0.5" id="modalScore" min="0" max="150" 
                        class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                </div>
                <div class="mb-5">
                    <label class="block text-sm font-medium text-gray-700 mb-1">考试类型</label>
                    <select id="modalExamType" class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                        <option value="月考">月考</option>
                        <option value="期中考试">期中考试</option>
                        <option value="期末考试">期末考试</option>
                        <option value="模拟考试">模拟考试</option>
                    </select>
                </div>
                <div class="mb-5">
                    <label class="block text-sm font-medium text-gray-700 mb-1">考试日期</label>
                    <input type="date" id="modalExamDate" 
                        class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                </div>
            </div>
            <div class="p-4 bg-gray-50 rounded-b-xl flex justify-end gap-3">
                <button onclick="closeModal()" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition duration-200">
                    取消
                </button>
                <button onclick="saveScore()" class="px-4 py-2 gradient-bg text-white rounded-lg hover:opacity-90 transition duration-200">
                    保存
                </button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentStudentId = null;
        let currentStudentData = null;
        let currentEditingRecord = null;

        // 获取URL参数
        function getParams() {
            const query = location.search.substring(1);
            const vars = query.split("&");
            const params = {};
            for (let i = 0; i < vars.length; i++) {
                const pair = vars[i].split("=");
                params[pair[0]] = decodeURIComponent(pair[1]);
            }
            return params;
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            const params = getParams();
			currentStudentId = params.id;
            if (currentStudentId) {
                loadStudentDetail();
            } else {
                showError('未找到学生ID');
            }
        });

        // 加载学生详情
        async function loadStudentDetail() {
            showLoading();
            
            try {
                const response = await fetch(`/pc/examScore/detail/${currentStudentId}`);
                const result = await response.json();
                
                if (result) {
					currentStudentData = result;
                    renderStudentDetail();
                } else {
                    showError(result.message || '加载失败');
                }
            } catch (error) {
                console.error('加载详情失败:', error);
                showError('网络错误，请检查连接');
            }
        }

        // 渲染学生详情
        function renderStudentDetail() {
            if (!currentStudentData) {
                showEmpty();
                return;
            }
			let urlparams = getParams();
            // 更新标题
            document.getElementById('studentNameTitle').textContent = 
                `${urlparams.studentName}的成绩详情`;
            document.getElementById('studentCampus').textContent = 
                `校区: ${urlparams.schoolName}`;

            // 渲染内容
            renderOverview();
            renderScores();
            
            // 显示内容
            document.getElementById('overviewCard').classList.remove('hidden');
            document.getElementById('scoresCard').classList.remove('hidden');
            document.getElementById('loadingState').classList.add('hidden');
            document.getElementById('emptyState').classList.add('hidden');
            document.getElementById('errorState').classList.add('hidden');
        }

        // 渲染成绩概览
        function renderOverview() {
            const container = document.getElementById('overviewContainer');
            container.innerHTML = '';

            if (!currentStudentData || currentStudentData.length === 0) {
                return;
            }

            const subjectConfig = {
                '语文': { color: 'chinese', icon: 'book' },
                '数学': { color: 'math', icon: 'calculator' },
                '英语': { color: 'english', icon: 'language' },
                '物理': { color: 'physics', icon: 'flask' },
                '化学': { color: 'chemistry', icon: 'beaker' }
            };

            let totalScore = 0;
            let subjectCount = 0;
            let totalExamCount = 0;

            // 渲染各科成绩
            currentStudentData.forEach(subject => {
                const config = subjectConfig[subject.subjectName];
                if (!config) return;

				const avgScore = subject.examRecords.length > 0 ? subject.examRecords[0].score : 0;
                const examCount = subject.examRecords ? subject.examRecords.length : 0;
                
                if (examCount > 0) {
                    totalScore += parseFloat(avgScore);
                    subjectCount++;
                    totalExamCount += examCount;
                }
				let contScore = 0;
				if(subject.examRecords.length>0){
					for(let i = 0; i<subject.examRecords.length; i++){
						contScore += subject.examRecords[i].score
					}
					contScore =  contScore / subject.examRecords.length;
				}
				
                const card = document.createElement('div');
                card.className = `text-center p-4 rounded-lg border border-${config.color}/20`;
                card.innerHTML = `
                    <div class="flex items-center justify-center mb-2">
                        <i class="fa fa-${config.icon} text-${config.color} mr-2"></i>
                        <span class="font-medium">${subject.subjectName}</span>
                    </div>
                    <div class="text-2xl font-bold text-${config.color}">${contScore.toFixed(1)}</div>
					<div class="text-xs text-gray-500 mt-1">${subject.examRecords.length}次考试</div>
                `;
                container.appendChild(card);
            });

            // 总体表现卡片
            const overallCard = document.createElement('div');
            overallCard.className = 'text-center p-4 rounded-lg border border-primary/20 md:col-span-2';
            const totalAvg = subjectCount > 0 ? (totalScore / subjectCount).toFixed(1) : '0.0';
            
            overallCard.innerHTML = `
                <div class="flex items-center justify-center mb-2">
                    <i class="fa fa-line-chart text-primary mr-2"></i>
                    <span class="font-medium">总体表现</span>
                </div>
                <div class="text-2xl font-bold text-primary">${totalAvg}</div>
                <div class="text-xs text-gray-500 mt-1">${totalExamCount}次考试</div>
            `;
            container.appendChild(overallCard);
        }

        // 渲染各科成绩记录
        function renderScores() {
            const container = document.getElementById('scoresContainer');
            container.innerHTML = '';

            if (!currentStudentData || currentStudentData.length === 0) {
                container.innerHTML = '<div class="text-center py-8 text-gray-500">暂无成绩记录</div>';
                return;
            }

            const subjectConfig = {
                '语文': { color: 'chinese' },
                '数学': { color: 'math' },
                '英语': { color: 'english' },
                '物理': { color: 'physics' },
                '化学': { color: 'chemistry' }
            };

            currentStudentData.forEach(subject => {
                const config = subjectConfig[subject.subjectName];
                if (!config) return;
				let contScore = 0;
				for(let i = 0; i<subject.examRecords.length; i++){
					contScore += subject.examRecords[i].score
				}
				let avgScore =  contScore / subject.examRecords.length;
                const subjectCard = document.createElement('div');
                subjectCard.className = 'border border-gray-200 rounded-lg overflow-hidden card-shadow fade-in';
                
                subjectCard.innerHTML = `
                    <div class="subject-header bg-${config.color}/10 text-${config.color}">
                        <div class="font-semibold" style="padding: 4px 12px;">${subject.subjectName}</div>
						<div class="flex items-center gap-4" style='padding: 0 12px 4px 12px;display: flex;justify-content: space-between;'>
							<span class="text-sm">平均分: <span class="font-bold">${avgScore ? avgScore.toFixed(1) : '0.0'}</span>
                            <button onclick="openAddModal(${subject.subjectId}, '${subject.subjectName}')" 
                                class="bg-white/80 hover:bg-white text-${config.color} px-3 py-1.5 rounded-lg text-sm font-medium transition duration-200">
                                <i class="fa fa-plus mr-1"></i> 添加成绩
                            </button>
                        </div>
                    </div>
                    <div class="scores-list">
                        ${renderExamRecords(subject.examRecords, subject.subjectId)}
                    </div>
                `;
                container.appendChild(subjectCard);
            });
        }

        // 渲染考试记录
        function renderExamRecords(records, subjectId) {
            if (!records || records.length === 0) {
                return '<div class="text-center py-8 text-gray-500">暂无成绩记录</div>';
            }

            return records.map((record, index) => `
                <div class="flex items-center justify-between py-3 px-5 border-t border-gray-50 hover:bg-gray-50 transition-colors duration-150">
                    <div class="flex items-center">
                        <span class="text-sm font-medium">第${index + 1}次考试</span>
                        <span class="text-xs text-gray-500 ml-2">${formatDate(record.examDate)} • ${record.examType || '考试'}</span>
                    </div>
                    <div class="flex items-center gap-4">
                        <span class="font-semibold text-lg">${record.score}</span>
                        <div class="flex gap-2">
                            <button onclick="openEditModal(${record.id}, ${subjectId})" 
                                class="text-gray-500 hover:text-primary transition-colors duration-200">
                                <i class="fa fa-pencil"></i>
                            </button>
                            <button onclick="deleteScore(${record.id})" 
                                class="text-gray-500 hover:text-danger transition-colors duration-200">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        // 打开添加模态框
        function openAddModal(subjectId, subjectName) {
            document.getElementById('modalTitle').textContent = `添加${subjectName}成绩`;
            document.getElementById('currentSubjectId').value = subjectId;
            document.getElementById('editScoreId').value = '';
            document.getElementById('modalScore').value = '';
            document.getElementById('modalExamType').value = '月考';
            document.getElementById('modalExamDate').value = new Date().toISOString().split('T')[0];
            
            currentEditingRecord = null;
            showModal();
        }

        // 打开编辑模态框
        function openEditModal(scoreId, subjectId) {
            const subject = currentStudentData.find(s => s.subjectId === subjectId);
            if (!subject || !subject.examRecords) return;
            
            const record = subject.examRecords.find(r => r.id === scoreId);
            if (!record) return;
            
            document.getElementById('modalTitle').textContent = `编辑${subject.subjectName}成绩`;
            document.getElementById('currentSubjectId').value = subjectId;
            document.getElementById('editScoreId').value = scoreId;
            document.getElementById('modalScore').value = record.score;
            document.getElementById('modalExamType').value = record.examType;
            document.getElementById('modalExamDate').value = formatDateForInput(record.examDate);
            
            currentEditingRecord = record;
            showModal();
        }

        // 保存成绩
        async function saveScore() {
            const scoreId = document.getElementById('editScoreId').value;
            const subjectId = document.getElementById('currentSubjectId').value;
            const score = parseFloat(document.getElementById('modalScore').value);
            const examType = document.getElementById('modalExamType').value;
            const examDate = new Date(document.getElementById('modalExamDate').value).getTime();

            // 验证数据
            if (isNaN(score) || score < 0 || score > 150) {
                showToast('请输入有效的分数（0-150之间）', 'error');
                return;
            }

            if (!examType) {
                showToast('请选择考试类型', 'error');
                return;
            }

            const scoreData = {
                id: scoreId || null,
                studentId: currentStudentId,
                subjectId: subjectId,
                score: score,
                examType: examType,
                examDate: examDate
            };

            try {
                const url = '/pc/examScore';
                const method = scoreId ? 'PUT' : 'POST';
                
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(scoreData)
                });

                if (response.status == 200) {
                    closeModal();
                    await loadStudentDetail();
                    showToast(response.message || (scoreId ? '修改成功' : '添加成功'), 'success');
                } else {
                    throw new Error(response.message || '操作失败');
                }
            } catch (error) {
                console.error('保存失败:', error);
                showToast(error.message || '操作失败', 'error');
            }
        }

        // 删除成绩
        async function deleteScore(scoreId) {
            if (!confirm('确定要删除这条成绩记录吗？')) return;

            try {
                const response = await fetch('/pc/examScore/del', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify([scoreId])
                });

                // const result = await response.json();
                
                if (response.status == 200) {
                    await loadStudentDetail();
                    showToast(response.message || '删除成功', 'success');
                } else {
                    throw new Error(response.message || '删除失败');
                }
            } catch (error) {
                console.error('删除失败:', error);
                showToast(error.message || '删除失败', 'error');
            }
        }

        // 显示模态框
        function showModal() {
            const modal = document.getElementById('examModal');
            modal.classList.remove('hidden');
            setTimeout(() => {
                modal.querySelector('.transform').classList.remove('scale-95');
                modal.querySelector('.transform').classList.add('scale-100');
            }, 10);
        }

        // 关闭模态框
        function closeModal() {
            const modal = document.getElementById('examModal');
            modal.querySelector('.transform').classList.remove('scale-100');
            modal.querySelector('.transform').classList.add('scale-95');
            setTimeout(() => {
                modal.classList.add('hidden');
            }, 300);
        }

        // 返回列表
        function goBack() {
            window.history.back();
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('loadingState').classList.remove('hidden');
            document.getElementById('overviewCard').classList.add('hidden');
            document.getElementById('scoresCard').classList.add('hidden');
            document.getElementById('emptyState').classList.add('hidden');
            document.getElementById('errorState').classList.add('hidden');
        }

        // 显示空状态
        function showEmpty() {
            document.getElementById('loadingState').classList.add('hidden');
            document.getElementById('overviewCard').classList.add('hidden');
            document.getElementById('scoresCard').classList.add('hidden');
            document.getElementById('emptyState').classList.remove('hidden');
            document.getElementById('errorState').classList.add('hidden');
        }

        // 显示错误状态
        function showError(message) {
            document.getElementById('loadingState').classList.add('hidden');
            document.getElementById('overviewCard').classList.add('hidden');
            document.getElementById('scoresCard').classList.add('hidden');
            document.getElementById('emptyState').classList.add('hidden');
            document.getElementById('errorState').classList.remove('hidden');
            document.getElementById('errorMessage').textContent = message;
        }

        // 工具函数
        function formatDate(timestamp) {
            if (!timestamp) return '未知日期';
            return new Date(timestamp).toLocaleDateString('zh-CN');
        }

        function formatDateForInput(timestamp) {
            if (!timestamp) return new Date().toISOString().split('T')[0];
            return new Date(timestamp).toISOString().split('T')[0];
        }

        // 显示提示消息
        function showToast(message, type = 'info') {
            const toast = document.createElement('div');
            toast.className = `toast ${type}`;
            toast.innerHTML = `
                <div class="flex items-center">
                    <i class="fa ${getToastIcon(type)} mr-2"></i>
                    <span>${message}</span>
                </div>
            `;
            
            document.body.appendChild(toast);
            
            setTimeout(() => toast.classList.add('show'), 10);
            
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        }

        function getToastIcon(type) {
            const icons = {
                'success': 'fa-check-circle',
                'error': 'fa-exclamation-circle',
                'warning': 'fa-exclamation-triangle',
                'info': 'fa-info-circle'
            };
            return icons[type] || 'fa-info-circle';
        }
    </script>
</body>
</html>